/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.sales.hancadso.client.view;

import br.com.sales.generics.client.components.autocomplete.widget.Autocomplete;
import br.com.sales.generics.client.components.scroll.HScroll;
import br.com.sales.generics.client.components.timepicker.HDateTimePicker;
import br.com.sales.generics.client.presenter.events.ShowLoadingEvent;
import br.com.sales.generics.client.presenter.events.ShowLoadingHandler;
import br.com.sales.hancadso.client.presenter.HanCadSOPresenter;
import br.com.sales.hancadso.client.presenter.HanCadSOUiHanlder;
import static br.com.sales.hancadso.client.presenter.consts.HanCadSOConsts.HEADER_ROW_INDEX;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RadioButton;
import com.google.gwt.user.client.ui.SourcesTableEvents;
import com.google.gwt.user.client.ui.TableListener;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.datepicker.client.CalendarUtil;
import com.google.inject.Inject;
import com.google.web.bindery.event.shared.EventBus;
import com.gwtplatform.mvp.client.ViewWithUiHandlers;
import com.sun.java.accessibility.util.AWTEventMonitor;
import java.util.Date;

/**
 *
 * @author v
 */
public class HanCadSOView extends ViewWithUiHandlers<HanCadSOUiHanlder> implements HanCadSOPresenter.Display, ShowLoadingHandler {

    private final static HanCadSoViewUiBinder uiBinder = GWT.create(HanCadSoViewUiBinder.class);
    private final HScroll mainContentScrollPanel = new HScroll();
    @UiField
    FlowPanel mainContentPanel;
    @UiField
    HTMLPanel container;
    @UiField
    Image loadingMessage;
    @UiField
    Button cancelBtn;
    @UiField
    Button saveBtn;
    @UiField
    Button newBtn;
    @UiField
    Button gridDetailBtn;
    @UiField
    HTMLPanel detailPanel;
    @UiField
    TextBox dateEdit;
    @UiField
    TextBox countEdit;
    @UiField
    VerticalPanel requesterEdit;
    @UiField
    VerticalPanel newProductEdit;
    @UiField
    HScroll flextableScroll;
    @UiField
    FlexTable itemsGrid;
    @UiField
    HDateTimePicker initialDate;
    @UiField
    HDateTimePicker finalDate;
    @UiField
    Image refreshBtn;
    @UiField
    HTMLPanel radioContainer;
    @UiField
    HTMLPanel filterContainer;
    @UiField
    Button addItem;
    @Inject
    private EventBus eventBus;
    private Autocomplete requesterComplete;
    private Autocomplete newProductComplete;

    private RadioButton aprovacaoOpt;
    private RadioButton encerramentoOpt;
    private RadioButton registroOpt;
    private RadioButton cancelamentoOpt;
    private RadioButton naoFiltrarOpt;

    @Inject
    public HanCadSOView() {
        uiBinder.createAndBindUi(this);
        flextableScroll.getElement().setId("myFlextableScroll");
    }

    private void createGrid() {
        itemsGrid.insertRow(HEADER_ROW_INDEX);
        itemsGrid.getRowFormatter().addStyleName(HEADER_ROW_INDEX, "flextable-header");

        addColumn("Produto");
        addColumn("Quantidade");
        addColumn("Editar");
        addColumn("Remover");

        itemsGrid.setCellSpacing(0);
        itemsGrid.addStyleName("flexttable");
        itemsGrid.getColumnFormatter().setWidth(0, "71%");
        itemsGrid.getColumnFormatter().setWidth(1, "100px");
        itemsGrid.addTableListener(new TableListener() {
            @Override
            public void onCellClicked(SourcesTableEvents sender,
                    int row, int cell) {
                if (row > 0) {
                    switch (cell) {
                        case 2: {
                            getUiHandlers().editRecorg(row);
                            break;
                        }
                        case 3: {
                            itemsGrid.removeRow(row);
                            break;
                        }
                    }
                }
            }
        });
    }

    @Override
    public void clearGrid() {
        int rouCount = itemsGrid.getRowCount();
        for (int i = rouCount - 1; i > 0; i--) {
            itemsGrid.removeRow(i);
        }
    }

    @Override
    public Widget createCellWidget(Object cellObject) {
        Widget widget;

        if (cellObject instanceof Widget) {
            widget = (Widget) cellObject;
        } else {
            widget = new Label(cellObject.toString());
        }
        return widget;
    }

    private void addColumn(Object columnHeading) {
        Widget widget = createCellWidget(columnHeading);
        int cell = itemsGrid.getCellCount(HEADER_ROW_INDEX);

        widget.addStyleName("flextable-column-label");

        itemsGrid.setWidget(HEADER_ROW_INDEX, cell, widget);

        itemsGrid.getCellFormatter().addStyleName(HEADER_ROW_INDEX, cell, "flextable-column-label-cell");
    }

    @Override
    public void build() {
        eventBus.addHandler(ShowLoadingEvent.TYPE, this);
        mainContentScrollPanel.setStyleName("container-product-scroll", true);
        requesterComplete = Autocomplete.build()
                .setAttributeNameDesc("NM_PESSOA_FISICA")
                .setAttributeNameID("NR_SEQUENCIA")
                .setIsMultiValued(false)
                .setTableName("PESSOA_FISICA");
        requesterEdit.add(requesterComplete);
        newProductComplete = Autocomplete.build()
                .setAttributeNameDesc("DS_PRODUTO")
                .setAttributeNameID("NR_SEQUENCIA")
                .setIsMultiValued(false)
                .setTableName("PRODUTO");
        newProductEdit.add(newProductComplete);
        dateEdit.setEnabled(false);
        loadingMessage.setVisible(false);
        createGrid();
        adjustMaxLength();
        setDateFilter();
        refreshBtn.setResource(HanCadSOResources.INSTANCE.refresh());
        addOnClickButton();
        createTipoDataGroup();
    }

    private void setDateFilter() {
        DateTimeFormat dtf = DateTimeFormat.getFormat("dd/MM/yyyy");
        Date data = new Date(System.currentTimeMillis());
        finalDate.setValue(dtf.format(data));
        CalendarUtil.addDaysToDate(data, -5);
        initialDate.setValue(dtf.format(data));
    }

    @Override
    public Widget asWidget() {
        return container;
    }

    @UiHandler("saveBtn")
    public void onClickSave(ClickEvent event) {
        getUiHandlers().onClickSave(event);
    }

    @UiHandler("newBtn")
    public void onClickNew(ClickEvent event) {
        getUiHandlers().onClickNew(event);
    }

    @UiHandler("cancelBtn")
    public void onClickCancel(ClickEvent event) {
        getUiHandlers().onClickCancel(event);
    }

    @UiHandler("gridDetailBtn")
    public void onClickGridDetail(ClickEvent event) {
        getUiHandlers().onClickGridDetail(event);
    }

    @UiHandler("addItem")
    public void onClickAddItem(ClickEvent event) {
        getUiHandlers().onClickAddItem(event);
    }

    @Override
    public boolean isMandatory(Boolean isEditing) {
        boolean isMandatory = false;
        if (("".equals(requesterComplete.getValue())
                || requesterComplete.getValue() == null)
                && isEditing) {
            requesterComplete.getElement().addClassName("mandatory");
            isMandatory = true;
        } else {
            requesterComplete.getElement().removeClassName("mandatory");
        }
        return isMandatory;
    }

    @Override
    public boolean isMandatorySubItem() {
        boolean isMandatory = false;
        if (("".equals(countEdit.getText())
                || countEdit.getText() == null)) {
            countEdit.getElement().addClassName("mandatory");
            isMandatory = true;
        } else {
            countEdit.getElement().removeClassName("mandatory");
        }
        if (("".equals(newProductComplete.getValue())
                || newProductComplete.getValue() == null)) {
            newProductComplete.getElement().addClassName("mandatory");
            isMandatory = true;
        } else {
            newProductComplete.getElement().removeClassName("mandatory");
        }
        return isMandatory;
    }

    private void adjustMaxLength() {
        countEdit.setMaxLength(4);
    }

    @Override
    public void setEnabled(boolean isNewrecord) {
        controlVisibleButton(isNewrecord);
        setEnabledField(isNewrecord);
    }
    
    public void setEnabledField(boolean enabled) {
        dateEdit.setEnabled(enabled);
        requesterComplete.setEnabled(enabled);
        newProductComplete.setEnabled(enabled);
        countEdit.setEnabled(enabled);
        addItem.setEnabled(enabled);
    }

    @Override
    public void controlVisibleButton(boolean isNewrecord) {
        cancelBtn.setVisible(isNewrecord);
        saveBtn.setVisible(isNewrecord);
        newBtn.setVisible(!isNewrecord);
        gridDetailBtn.setVisible(!isNewrecord);
    }

    private void setMainContentScroll(IsWidget content) {
        mainContentScrollPanel.clear();
        mainContentPanel.clear();

        if (content != null) {
            mainContentScrollPanel.add(content);
            mainContentPanel.add(mainContentScrollPanel);
        }
    }

    @Override
    public void setInSlot(Object slot, IsWidget content) {
        if (slot == HanCadSOPresenter.HANCADSO_SLOT_TYPE) {
            setMainContentScroll(content);
        }
    }

    @Override
    public FlexTable getItemsGrid() {
        return itemsGrid;
    }

    @Override
    public Image getLoadingMessage() {
        return loadingMessage;
    }

    @Override
    public HTMLPanel getDetailPanel() {
        return detailPanel;
    }

    @Override
    public TextBox getDateEdit() {
        return dateEdit;
    }

    @Override
    public TextBox getCountEdit() {
        return countEdit;
    }

    @Override
    public Autocomplete getRequesterComplete() {
        return requesterComplete;
    }

    @Override
    public HScroll getMainContentScrollPanel() {
        return mainContentScrollPanel;
    }

    @Override
    public Autocomplete getNewProductComplete() {
        return newProductComplete;
    }

    @Override
    public void showLoading(boolean show) {
        loadingMessage.setVisible(show);
    }

    @Override
    public HDateTimePicker getInitialDate() {
        return initialDate;
    }

    public void setInitialDate(HDateTimePicker initialDate) {
        this.initialDate = initialDate;
    }

    @Override
    public HDateTimePicker getFinalDate() {
        return finalDate;
    }

    public void setFinalDate(HDateTimePicker finalDate) {
        this.finalDate = finalDate;
    }

    public Image getRefreshBtn() {
        return refreshBtn;
    }

    public void setRefreshBtn(Image refreshBtn) {
        this.refreshBtn = refreshBtn;
    }

    @Override
    public HTMLPanel getFilterContainer() {
        return filterContainer;
    }

    private void addOnClickButton() {
        refreshBtn.addClickHandler(new ClickHandler() {

            @Override
            public void onClick(ClickEvent event) {
                getUiHandlers().onClickRefresh(event);
            }
        });

    }

    private void createTipoDataGroup() {
        aprovacaoOpt = new RadioButton("tipoDataGroup", "Aprovação");
        cancelamentoOpt = new RadioButton("tipoDataGroup", "Cancelamento");
        encerramentoOpt = new RadioButton("tipoDataGroup", "Encerramento");
        registroOpt = new RadioButton("tipoDataGroup", "Registro");
        naoFiltrarOpt = new RadioButton("tipoDataGroup", "Não filtrar");

        radioContainer.add(aprovacaoOpt);
        radioContainer.add(cancelamentoOpt);
        radioContainer.add(encerramentoOpt);
        radioContainer.add(registroOpt);
        radioContainer.add(naoFiltrarOpt);
        
        aprovacaoOpt.setValue(Boolean.TRUE);

    }

    @Override
    public HTMLPanel getRadioContainer() {
        return radioContainer;
    }

    @Override
    public RadioButton getAprovacaoOpt() {
        return aprovacaoOpt;
    }

    @Override
    public RadioButton getEncerramentoOpt() {
        return encerramentoOpt;
    }

    @Override
    public RadioButton getRegistroOpt() {
        return registroOpt;
    }

    @Override
    public RadioButton getCancelamentoOpt() {
        return cancelamentoOpt;
    }
    
        @Override
    public RadioButton getNaoFiltrarOpt() {
        return naoFiltrarOpt;
    }

    interface HanCadSoViewUiBinder extends UiBinder<HTMLPanel, HanCadSOView> {
    }
}
